#include "QuadTree.h"
#include "ResourceManager.h"
#include "Brick.h"
#include "Turtle.h"
#include "Grass.h"

QuadTree::QuadTree()
{
	
}

QuadTree::~QuadTree()
{
	if (root != NULL)
	{
		delete root;
	}
}
int QuadTree::Clip(int x1, int x2, int x3, int x4)
{
	
	if(((x1 < x3)&&(x2> x3)&&(x2<=x4))
		||((x1 >= x3)&&(x2<=x4))
		||((x1 >= x3)&&(x1<x4)&&(x2>x4))
		||(x1<x3)&&(x2>x4))
	{
		return 1;
	}
	else
	{
		return 0;
	}
	
}

int QuadTree::ClipXY(Node * node, RECT view)
{
	if((Clip(view.left,view.right,node->_x1,node->_x2)==1)&&(Clip(view.bottom,view.top,node->_y2,node->_y1))==1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
} 

void QuadTree::ClipView(Node * node, RECT view, list<Object*>* _listObject)
{
	if(ClipXY(node,view)==1)
	{
		
		if(node->lt!=NULL)
		{
			ClipView(node->lt,view,_listObject);		
			ClipView(node->lb,view, _listObject);
			ClipView(node->rt,view, _listObject);
			ClipView(node->rb,view, _listObject);
		}
		else
		{
			Object *_obj;

			list<Object*>::iterator k;
			for (k = node->_list.begin(); k != node->_list.end(); k++)
				{
					_obj = *k;
					if(!(_obj->getObjState() == 0))
					{
						bool is_drawed = false;
						Object *_objectDrawed;
						list<Object*>::iterator i = _listObject->begin();
						while (i != _listObject->end() && is_drawed == false)
						{
							_objectDrawed = *i;
							if (_obj->getIDObj() == _objectDrawed->getIDObj())
							{
								is_drawed = true;

							}
							++i;
						}
						if (is_drawed == false)
						{
							_listObject->push_back(_obj);
						}
					}
			}
		}
	}
}

void QuadTree::getObjectFromCamara(RECT camara_rect, list<Object*>* _listObject)
{
	ClipView(this->root, camara_rect, _listObject);

}

